package com.enhinck.dbutilweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.enhinck.dbutilweb.common.WebResponse;
import com.enhinck.dbutilweb.common.database.ConnectionWrapper;
import com.enhinck.dbutilweb.common.database.DbPoolUtil;
import com.enhinck.dbutilweb.common.database.MysqlDBUtil;
import com.enhinck.dbutilweb.config.SqlExecUtil;
import com.enhinck.dbutilweb.model.TableColumnVO;
import com.enhinck.dbutilweb.model.TableStructVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 数据源比较管理
 *
 * @author enhinck Generate auto created
 * @date 2021-03-03 10:52:04
 */
@Slf4j
@Api(description = "数据源新增表工具", tags = {"DatasourceStructAddController"})
@RestController
@AllArgsConstructor
public class DatasourceStructAddController {
    private final DbPoolUtil dbPoolUtil;
    private final MysqlDBUtil mysqlDBUtil;


    /**
     * [
     * {"column":"HHH",
     * "columnType":"bigint(20)",
     * "isNullable":"true",
     * "columnDefault":"JJ",
     * "columnComment":"22",
     * "extra":"auto_increment",
     * "columnKey":"true"}
     * ]
     */

    /**
     * 数据库表列表
     *
     * @return
     */
    /**
     * @param tableStructVO 新表结构
     * @return
     */
    @ApiOperation("数据库表中字段列表")
    @PostMapping("/datasource/table")
    public WebResponse<List<Map<String, Object>>> ddl(@RequestBody TableStructVO tableStructVO) {
        log.info("{}", JSONObject.toJSONString(tableStructVO));

        ConnectionWrapper connectionWrapper = null;
        Long id = tableStructVO.getId();
        try {
            connectionWrapper = dbPoolUtil.getConnection(id);


            String ddl = convertDDL(tableStructVO);

            log.info("\n{}", ddl);
             SqlExecUtil.Result result = SqlExecUtil.execute(connectionWrapper.getConnection(), ddl);
             connectionWrapper.setLastQueryTime(System.currentTimeMillis());
            List<Map<String, Object>> datas = new ArrayList<>();
            Map<String, Object> data = new HashMap<>();
            data.putAll((JSONObject) JSONObject.toJSON(result));
            datas.add(data);
            return WebResponse.ok(datas);
        } catch (Exception e) {
            log.error("{}", e);
            return WebResponse.error("400", "数据库获取链接失败");
        } finally {
            dbPoolUtil.release(connectionWrapper);
        }
    }

    private String convertDDL(TableStructVO tableStructVO) {

        String tableName = tableStructVO.getTableName();

        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append("CREATE TABLE `").append(tableName).append("` (\n");
        List<TableColumnVO> columnVOS = tableStructVO.getColumns();

        Boolean hasPK = false;
        String pkName = "";
        Boolean hasAutoIncrement = false;
        for (int i = 0; i < columnVOS.size(); i++) {
            TableColumnVO columnVO = columnVOS.get(i);
            Boolean isNotNull = columnVO.getIsNotNull();
            String notNull = " ";
            if (isNotNull) {
                notNull = " NOT NULL ";
            }
            String columnDefault = columnVO.getColumnDefault();
            if (StringUtils.isBlank(columnDefault)){
                columnDefault = " ";
            }else {
                columnDefault = " DEFAULT " + columnDefault;
            }
            String autoIncrement = " ";
            if (columnVO.getAutoIncrement()&&columnVO.getColumnKey()){
                autoIncrement = "AUTO_INCREMENT";
                hasAutoIncrement = true;
            }
            sqlBuilder.append("`").append(columnVO.getColumnName()).append("` ")
                    .append(columnVO.getColumnType())
                    .append(notNull)
                    .append(columnDefault)
                    .append(autoIncrement)
                    .append(" COMMENT '").append(columnVO.getColumnComment()).append("',\n");
            // 仅允许一个主键，第一个为主键
            if (columnVO.getColumnKey()&&!hasPK){
                hasPK = true;
                pkName = columnVO.getColumnName();
            }
        }

        if (hasPK){
            sqlBuilder.append("PRIMARY KEY (`").append(pkName).append("`)\n");
        }else {
            sqlBuilder.deleteCharAt(sqlBuilder.length()-2);
        }

        String autoIncrement = " ";
        if (hasAutoIncrement){
            autoIncrement = " AUTO_INCREMENT=1 ";
        }
        sqlBuilder.append(") ENGINE=InnoDB").append(autoIncrement).append("DEFAULT CHARSET=utf8mb4 COMMENT='").append(tableStructVO.getTableComment()).append("';");

        /**
         * CREATE TABLE `event_rule_senior_calculation` (
         *   `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
         *   `rule_id` varchar(32) NOT NULL DEFAULT '' COMMENT '规则id',
         *   `senior_calculation_type` varchar(32) NOT NULL DEFAULT '' COMMENT '高级计算类型',
         *   `condition_id` varchar(32) NOT NULL DEFAULT '' COMMENT '规则条件id',
         *   `interval` int(11) NOT NULL DEFAULT '' COMMENT '指定时间内（秒）',
         *   `expr` varchar(100) NOT NULL DEFAULT '==' COMMENT '表达式',
         *   `value` varchar(100) NOT NULL DEFAULT '' COMMENT '值',
         *   `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:0无效 1有',
         *   `gmt_create` bigint(20) DEFAULT NULL COMMENT '创建时间',
         *   `gmt_modified` bigint(20) DEFAULT NULL COMMENT '修改时间',
         *   PRIMARY KEY (`id`)
         * ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='规则高级计算配置';
         */

        return sqlBuilder.toString();
    }

}